import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:xinmubiao/global.dart';
import 'package:xinmubiao/api.dart';
import 'dart:ui';

import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';

class NewsDetailPage extends StatefulWidget {
  NewsDetailPage({Key key, this.id, this.title}) : super(key: key);
  final id;
  final String title;
  @override
  _NewsDetailPageState createState() => _NewsDetailPageState();
}

class _NewsDetailPageState extends State<NewsDetailPage> {
  var _data;

  AudioPlayer audioPlayer = AudioPlayer();
  StreamSubscription _durationSubscription;
  // 音频总时间
  Duration duration;
  // 音频当前时间
  Duration position = Duration(milliseconds: 0);
  // 音频是否正在播放
  bool complete = false;
  bool circlePlay = false;
  // 进度条进度值
  double sliderValue = 0;

  String dText = '--:--';
  String pText = '--:--';

  // 开始播放
  play() async {
    try {
      final result = await audioPlayer.play(_data['audio'], position: position);
      audioPlayer.setPlaybackRate(playbackRate: 1.0);
      if (result == 1) setState(() => {complete = true});
    } catch (e) {
      print(e);
    }
  }

  // 暂停播放
  void pause() async {
    final result = await audioPlayer.pause();
    if (result == 1) {
      setState(() {
        complete = false;
      });
    }
  }

  //停止播放
  void stop() {
    audioPlayer.stop();
  }

  void setSeek(seek) {
    audioPlayer.seek(seek);
  }

  @override
  void initState() {
    getData();
    audioPlayer.onPlayerStateChanged.listen((state) {
      // 播放完毕
      if (state == AudioPlayerState.COMPLETED) {
        // 重置时长及播放状态
        setState(() {
          position = Duration(milliseconds: 0);
          // duration = Duration(milliseconds: 0);
          sliderValue = 0;
          complete = false;
        });
        // if (circlePlay) play();
      }
    });

    _durationSubscription = audioPlayer.onDurationChanged.listen((d) {
      setState(() {
        duration = d;
        dText = getPositionText(duration);
      });
    });

    // 播放进度监听
    audioPlayer.onAudioPositionChanged.listen((Duration p) {
      setState(() {
        position = p;
        pText = getPositionText(position);
        try {
          var _value = position.inMilliseconds / duration.inMilliseconds;
          if (_value >= 0 && _value < 1) {
            sliderValue = _value;
          }
        } catch (e) {
          print(e);
          sliderValue = 0;
        }
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    _durationSubscription?.cancel();
    stop();
    super.dispose();
  }

  getData() async {
    setState(() => {_data = null});
    var res = await detail(widget.id);
    setState(() => {_data = res});
  }

  String getPositionText(position) {
    return position?.toString()?.split('.')?.first?.substring(2) ?? '';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title == null ? '新目标英语九年级' : widget.title,
          style: TextStyle(
            color: Global.backgroundColor,
            fontSize: 13,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: Global.primaryColor,
        brightness: Brightness.light,
        elevation: 20,
      ),
      body: _data == null
          ? Container(
              color: Global.backgroundColor,
              child: Center(
                child: CircularProgressIndicator(
                  backgroundColor: Global.backgroundColor,
                  valueColor:
                      AlwaysStoppedAnimation<Color>(Global.primaryColor),
                ),
              ),
            )
          : Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              decoration: BoxDecoration(
                color: Global.backgroundColor,
              ),
              child: Column(
                children: [
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          Container(
                            margin: EdgeInsets.all(12),
                            child: Html(
                              data: _data['content'],
                              style: {
                                ".qh_en": Style(
                                  color: Global.primaryColor,
                                  fontWeight: FontWeight.w400,
                                  fontSize: FontSize.percent(100),
                                  margin: EdgeInsets.fromLTRB(0, 15, 0, 15),
                                ),
                                ".qh_zg": Style(
                                  color: Global.fontColor,
                                  fontWeight: FontWeight.w400,
                                  fontSize: FontSize.percent(100),
                                  margin: EdgeInsets.fromLTRB(0, 15, 0, 15),
                                ),
                                "img": Style(
                                  width: MediaQuery.of(context).size.width,
                                ),
                                "#source": Style(
                                  color: Global.backgroundColor,
                                ),
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Container(
                    width: MediaQuery.of(context).size.width,
                    padding: EdgeInsets.only(bottom: 20),
                    decoration: BoxDecoration(
                      color: Global.backgroundColor,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.15),
                          offset: Offset(0, -5),
                          blurRadius: 5,
                          spreadRadius: 1,
                        )
                      ],
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 300,
                          height: 60,
                          margin: EdgeInsets.all(5),
                          padding: EdgeInsets.fromLTRB(20, 5, 20, 5),
                          decoration: BoxDecoration(
                            color: Global.primaryColor.withOpacity(.2),
                            borderRadius: BorderRadius.circular(100),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              InkWell(
                                onTap: () {
                                  complete ? pause() : play();
                                },
                                child: Container(
                                  child: Icon(
                                    complete
                                        ? Icons.pause_circle_filled
                                        : Icons.play_circle_fill,
                                    color: Global.fontColor.withOpacity(.6),
                                    size: 48,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: Stack(
                                  children: [
                                    Positioned(
                                      top: 10,
                                      left: 20,
                                      right: 43,
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            pText,
                                            style: TextStyle(
                                              color: Global.primaryColor,
                                              fontSize: 12,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                          Text(
                                            dText,
                                            style: TextStyle(
                                              color: Global.primaryColor,
                                              fontSize: 12,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    Positioned(
                                      top: 10,
                                      left: 0,
                                      child: SliderTheme(
                                        data: SliderTheme.of(context).copyWith(
                                          activeTrackColor: Global.primaryColor
                                              .withOpacity(.5), //进度条滑块左边颜色
                                          inactiveTrackColor: Global
                                              .primaryColor
                                              .withOpacity(.3), //进度条滑块右边颜色
                                          thumbColor:
                                              Global.primaryColor, //滑块颜色
                                          overlayColor:
                                              Colors.transparent, //滑块拖拽时外圈的颜色
                                          trackHeight: 2, //进度条宽度
                                          thumbShape: RoundSliderThumbShape(
                                            enabledThumbRadius: 6, //滑块大小
                                          ),
                                        ),
                                        child: Slider(
                                          onChanged: (v) {
                                            final p =
                                                v * duration.inMilliseconds;
                                            setSeek(Duration(
                                                milliseconds: p.round()));
                                          },
                                          value: sliderValue,
                                          max: 1,
                                          min: 0,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}
